package it.sd.wdc.spider.htmlbrowser;

import it.sd.wdc.spider.bean.PostParameters;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.omg.CORBA.portable.ResponseHandler;

/**
 * La classe contiene i metodi necessari per scaricare le pagine HTML da un
 * server web, inoltre contiene alcuni metodi di servizio usati per preparare la
 * chiamata ai metodi di navigazione
 */
public class WebTcpClientSession {

	private HttpClient httpClient = null;

	public WebTcpClientSession(HttpClient client) {
		httpClient = client;
	}

	/*
	public byte[] getBinaryPage(String url, PostParameters postData)
			throws WebClientException {

		HttpGet get = null;

		try {

			get = new HttpGet(url + "?" + postData.getPostAsString());

			WebTcpResponseHandlerByte handler = new WebTcpResponseHandlerByte();
			byte[] body = httpClient.execute(get, handler);

			return body;
		} catch (Exception e) {
			throw new WebClientException(e.getMessage());
		} finally {
			try {
				get.abort();
			} catch (Exception e1) {
			}
		}
	}
*/

	public String getPage(String url) throws WebClientException {

		String action = null;
		String host = null;
		
		if (url.startsWith("http://")) {
			url = url.substring(7);
		} else if (url.startsWith("https://")) {
			url = url.substring(8);
		}
		
		int pos = url.indexOf("/");
		if (pos>-1) {
			host = url.substring(0, pos);
			action = url.substring(pos);
		} else {
			action = "/";
			host = url;
		}
		
		return getPage(host, action, "GET", new PostParameters());

	}

	public String getPage(String host, String action, String method, PostParameters postData)
			throws WebClientException {

		String strPageHTML = null;

		HttpMethodBase base = null;

		try {
			base = getMethod(method, host, action, postData);

			httpClient.executeMethod(base);
			
			strPageHTML = base.getResponseBodyAsString();

		} catch (Exception e) {
			throw new WebClientException(e.getMessage(), e);
		} finally {
			try {
				base.releaseConnection();;
			} catch (Exception e1) {
			}
		}

		return strPageHTML;
	}

	private HttpMethodBase getMethod(String method, String url, String action, PostParameters postData) 
				throws Exception  {

		List<NameValuePair> nvps = getParameter(postData.getNameValuePair());

		if ("POST".equalsIgnoreCase(method)) {
			PostMethod post = new PostMethod(url);
			return post;
		} else {
			GetMethod get = new GetMethod(url + action);
			get.setQueryString(postData.getPostAsString());
			return get;
		}
		
	}
	
	public HttpClient getHttpClient() {
		return httpClient;
	}

	private LinkedList<NameValuePair> getParameter(LinkedList<String[]> params) {
		LinkedList<NameValuePair> valori = new LinkedList<NameValuePair>();

		for (Iterator<String[]> iterator = params.iterator(); iterator
				.hasNext();) {
			String[] c = iterator.next();
			NameValuePair nvp = new NameValuePair(c[0], c[1]);
			valori.add(nvp);
		}

		return valori;
	}
	
	public void close() {
//		try {
//			httpClient.
//			httpClient.getConnectionManager().shutdown();
//		} catch (Exception e1) {
//			Logger.getLogger(this.getClass()).error(
//					"Errore chiusura connessione", e1);
//		}
	}
}
